import React, { useImperativeHandle, useMemo, useRef, useState } from "react";
import { Button, CheckBox, Popup } from "devextreme-react";
import { DevGrid, DevPopup } from "~/public/cpas-ui";
import { columns } from "./SimpleDatas";
import { getRollBillList, rollBills, rollReCal } from "./service";
import { useModel } from "umi";
import notify from "devextreme/ui/notify";
import * as ReactDOMClient from 'react-dom/client';
import "./index.less";
import { Checkbox } from "antd";


const AdjustmentPopup = React.forwardRef((props: any, ref) => {
    const { initialState } = useModel('@@initialState');
    const { dbname } = initialState?.curPart as API.CurPart;
    const { username, usercode } = initialState?.curUser as API.CurUser;
    const { reloadDevTable, currentSjnd } = props;
    const [visible, setVisible] = useState<boolean>(false);
    const [batchBillID, setBatchBillID] = useState<any[]>([]);
    const [billNoData, setBillNoData] = useState<any[]>([]);
    const tipsPopupRef = useRef<any>();
    const devGridRef = useRef<any>();

    const [devTableData, setDevTableData] = useState<any[]>([]);

    // 自定义方法
    useImperativeHandle(ref, () => ({
        show: (PopupData: any[]) => {
            // gridData.current = PopupData;
            devGridRef.current.instance.clearFilter();
            setDevTableData(PopupData);
            setVisible(true);
        },
        close: () => { setVisible(false); }
    }));

    const onCellClickDelte = (data: any, isAdd: boolean) => {
        if (data.BillID) {
            if (isAdd) {
                setBatchBillID((arr: any) => {
                    const ars = [...arr];
                    ars.push(data.BillID);
                    return [...new Set(ars)];
                });
            } else {
                setBatchBillID((arr: any) => {
                    let ars = [...arr];
                    ars = ars.filter((item: string) => item != data.BillID);
                    return [...new Set(ars)];
                });
            }
        }
    }


    const startBoll = async () => {
        if (!currentSjnd) return notify(`获取单据滚调到年度失败！`, "error", 2000);
        const res = await rollBills({
            dbname,
            billIDs: batchBillID.join(";"),
            trueName: username,
            userCode: usercode
        })
        if (res.success) {
            setVisible(false);
            notify(`单据滚调到本期期初成功！`, "success", 2000);
            const resReCal = await rollReCal({
                dbname,
                editUser: username,
                isRecalTZ: true,
                Data_ID: currentSjnd
            });
            if (resReCal.success) {
                reloadDevTable();
            }

        } else {
            notify(`失败：${res.data}`, "error", 2000);
        }
    }


    const BatchClick = async () => {
        setBillNoData([]);
        const resBillList = await getRollBillList({
            dbname: dbname,
            billIDs: batchBillID.join(";")
        });

        if (resBillList.success) {
            if (resBillList.data.length > 0) {
                const billData = resBillList.data.map((item: { billNo: string }) => item.billNo);
                const newbillData = [...new Set(billData)];
                setBillNoData(newbillData);
                tipsPopupRef.current.show({
                    title: "提示",
                    okCallback: () => {
                        startBoll();
                    }
                })
            } else {
                startBoll();
            }
        }
    }

    return (
        <>
            <Popup
                ref={ref}
                title="上年期末调整事项"
                // dragOutsideBoundary={true}
                // resizeEnabled={true}
                visible={visible}
                width={1250}
                minHeight={430}
                {...props}
                hideOnOutsideClick={true}
                onHiding={() => {
                    setVisible(false);
                    setDevTableData([]);
                    setBatchBillID([]);
                    setBillNoData([]);
                    devGridRef.current.instance.clearFilter();
                }}
            >

                <div style={{ width: '100%', height: "calc(100% - 50px)", marginBottom: '20px' }}>
                    {useMemo(() => {
                        return <DevGrid.RangeTap
                            height='100%'
                            width="100%"
                            dataSource={devTableData}
                            keyExpr="guidKey"
                            className="AdjustmentDevTable PaperDevSortableGrid devHeadersCenter"
                            ref={devGridRef}
                            defaultColumns={[...columns, {
                                dataField: "GroupInfo",
                                dataType: "string",
                                caption: "组信息",
                                width: 120,
                                alignment: "center",
                                groupIndex: 0,
                                groupCellTemplate: (cellElement: any, options: any) => {
                                    return ReactDOMClient.createRoot(cellElement).render(<>
                                        <Checkbox className='SubjectsCheckBox'
                                            onChange={(e: any) => {
                                                if (options.data.items) {
                                                    onCellClickDelte(options.data.items[0], e.target.checked)
                                                } else {
                                                    onCellClickDelte(options.data.collapsedItems[0], e.target.checked)
                                                }
                                            }}>
                                            <span style={{ color: '#333' }}>{options.value}</span>
                                        </Checkbox>
                                    </>)
                                }
                            }]
                            }
                            showBorders={true}
                            showRowLines={true}
                            showColumnLines={true}
                            onOptionChanged={(e) => {
                                if (e.fullName === "searchPanel.text" || e.fullName === "onOptionChanged") {
                                    setBatchBillID([]);
                                }
                            }}
                            searchPanel={{
                                visible: true,
                                width: 180,
                                placeholder: '',
                            }}
                            paging={{
                                enabled: false
                            }}
                            grouping={{
                                autoExpandAll: true
                            }}
                            groupPanel={{
                                visible: false
                            }}
                        />
                    }, [devTableData])}
                </div>
                <div style={{
                    display: 'flex',
                    flexDirection: 'row-reverse',
                    alignContent: 'center'
                }}>
                    <Button type='default' text='滚调到本期期初' onClick={() => {
                        if (batchBillID.length > 0) {
                            BatchClick()
                        } else {
                            notify(`请选择需要滚调的单据`, "warning", 2000);
                        }
                    }} />
                </div>
            </Popup >
            <DevPopup.Default ref={tipsPopupRef} width={80} height={200} >
                {() => {
                    return <span>{`检测到单据编号：【${billNoData.join("、")}】已滚调，是否重复滚调？`}</span>
                }}
            </DevPopup.Default>

        </>
    )
});


export default AdjustmentPopup;